﻿using AutoMapper;
using Common;
using Common.AJControls;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Utility;
using Common.Utility.AJ;
using Common.Utility.AJ.Extension;
using Common.ViewModels;
using MaterialDesignThemes.Wpf;
using Stylet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace AWSV2.ViewModels
{
    public class ICViewModel : Screen
    {
        private IWindowManager _windowManager;
        private AJTableImportOptions _importOptions;

        private AWSV2.Services.ICCard _icSvc;

        #region 分页配置

        private AJTablePagination _pagination;
        public AJTablePagination Pagination
        {
            get
            {
                return _pagination;
            }
            set
            {
                SetAndNotify(ref _pagination, value);
            }
        }

        public void PrevOrNextPageChangeCmd(string parameter)
        {
            var changed = false;
            var prev = parameter.Contains('上');
            if (prev)
            {
                if (Pagination.CanPrevPage)
                {
                    Pagination.Current -= 1;
                    changed = true;
                }
            }
            else
            {
                if (Pagination.CanNextPage)
                {
                    Pagination.Current += 1;
                    changed = true;
                }
            }

            if (changed)
            {
                ExecuteGetListCmd(null);
            }
        }

        public void PageItemCheckedCmd(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
            if (e.OriginalSource is ToggleButton tgb)
            {
                var parameter = tgb.DataContext as AJTablePageItem;
                if (parameter.PageNumber.Equals("···"))
                {
                    var prev = parameter.IsPageJumper == true;
                    var current = prev
                        ? new int[] { 1, Pagination.Current - 5 }.Max()
                        : new int[] { Pagination.Total, Pagination.Current + 5 }.Min();

                    Pagination.Current = current;
                    return;
                }
                Pagination.Current = Convert.ToInt32(parameter.PageNumber);
                ExecuteGetListCmd(null);
            }

        }

        #endregion

        private bool _loading;
        public bool Loading
        {
            get
            {
                return _loading;
            }
            set
            {
                SetAndNotify(ref _loading, value);
            }

        }

        private BindableCollection<ICCard> _rows;
        public BindableCollection<ICCard> Rows
        {
            get
            {
                return _rows;
            }
            set
            {
                SetAndNotify(ref _rows, value);
            }

        }

        private ICCard _current;
        public ICCard Current
        {
            get => _current;
            set => SetAndNotify(ref _current, value);
        }

        public string _search;
        public string Search
        {
            get
            {

                return _search;
            }
            set
            {
                _search = value;
            }
        }

        private string _currentReadCardId;

        public ICViewModel(IWindowManager windowManager)
        {
            _windowManager = windowManager;
            _icSvc = new Services.ICCard();
            Pagination = new AJTablePagination();

            Rows = new BindableCollection<ICCard>();

            _importOptions = new AJTableImportOptions
            {
                ImportType = typeof(ICCardExcelModel),
                TemplateRowsHandler = () =>
                {
                    var txt = I18NService.Translate(LangKeys.选填_0_, string.Empty);
                    return new List<object> {
                        new ICCardExcelModel
                        {
                            CardId = $"{I18NService.Translate(LangKeys.必填)},{I18NService.Translate(LangKeys.如_0_,"0001")}",
                            CustomerName = txt,
                            GoodsName = txt,
                            CarNo = txt,
                            GoodsSpecName = txt,
                            Fhdw = txt,
                            By1 = txt,
                            By2 = txt,
                            By3 = txt,
                            By4 = txt,
                            By5 = txt,
                        }
                    };
                },
                ImportDataItemProcessHandler = (rows) =>
                {
                    using var ctrl = new ICCardController();
                    var mapper = AJAutoMapperService.Instance().Mapper;
                    var rowList = rows.Select(p => (ICCard)((ICCardExcelModel)p)).ToList();
                    var importForm = new Common.EF.Tables.ICCardBatchImportForm();
                    var importTask = Task.Run(() =>
                    {
                        importForm.Rows = mapper.Map<List<ICCard>, List<Common.EF.Tables.ICCard>>(rowList);
                        return ctrl.Import(importForm);
                    });
                    importTask.Wait();
                    return importTask.Result;
                },
                ImportCompleteHandler = () =>
                {
                    var result = new ProcessResult();
                    result.SetSuccess();
                    return Task.FromResult(result);
                }

            };

            //ExecuteGetListCmd(null);
        }

        public void OnSearchKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ExecuteGetListCmd(null);
            }
        }

        public void OpenExportDialog()
        {
            using var ctrl = new ICCardController();
            var mapper = AJAutoMapperService.Instance().Mapper;
            _ = _windowManager.ShowDialog(new AJExportDialogViewModel(
                I18NService.Translate(LangKeys._0_导出__1_, I18NService.Translate(LangKeys.IC卡), DateTime.Now.ToString("yyyyMMdd_HHmm")),
                    (pageCfg) =>
                    {
                        return Task.Run(async () =>
                        {
                            var paged = await ctrl.Pages(Search, pageCfg.Current, pageCfg.PageSize);

                            return new AJTableFetchResult
                            {
                                HasNext = paged.HasNext,
                                Total = paged.TotalCount,
                                Rows = (mapper.Map<List<Common.EF.Tables.ICCard>, List<ICCard>>(paged.Data))
                                .Select(p => (ICCardExcelModel)p).ToList()
                            };
                        });
                    }
                ));
        }

        public void OpenImportDialog()
        {
            bool? result = _windowManager.ShowDialog(new ImportExcelDialogViewModel(_importOptions));

            if (result.GetValueOrDefault(true))
            {
                ExecuteGetListCmd(null);
            }
        }

        public void OpenForm(bool addMode)
        {
            var viewModel = new ICCardDetailViewModel(addMode ? null : _current, _currentReadCardId);
            bool? result = _windowManager.ShowDialog(viewModel);

            if (result.GetValueOrDefault(true))
            {
                ExecuteGetListCmd(null);
            }
        }

        #region 行选择功能 --阿吉 2024年4月25日10点43分

        private CheckBox _allRowCheckbox;
        private bool _allRowCheckboxProcess;

        public string CurrentLoginId { get; set; } = Globalspace._currentUser.LoginId;

        private bool _canDeleteSelected;
        public bool CanDeleteSelected
        {
            get
            {
                _canDeleteSelected = Rows.Any(p => p.Checked);
                return _canDeleteSelected;
            }
            set { SetAndNotify(ref _canDeleteSelected, value); }
        }


        public async void DeleteSelected()
        {
            var selected = Rows.Where(p => p.Checked).ToList();

            var result = MessageBox.Show(I18NService.Translate(LangKeys.确认删除_0_条数据吗, selected.Count),
                 I18NService.Translate(LangKeys.提示), MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                using var ctrl = new ICCardController();
                var deleteRet = await ctrl.MultiDelete(selected.Select(p => p.Id));

                if (deleteRet == 0)
                {
                    MessageBox.Show(I18NService.Translate(LangKeys.未删除任何数据), I18NService.Translate(LangKeys.删除失败), MessageBoxButton.OK);
                    return;
                }

                ExecuteGetListCmd(null);

            }
        }

        public void RowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            if (_allRowCheckboxProcess)
            {
                return;
            }
            var cbx = ((CheckBox)sender);
            var view = cbx.DataContext as ICCard;
            if (view == null)
            {
                return;
            }

            view.Checked = cbx.IsChecked.GetValueOrDefault();

            var checkedCount = 0;

            foreach (var row in Rows)
            {
                if (row.Checked)
                {
                    checkedCount++;
                }
            }

            _allRowCheckbox.IsThreeState = checkedCount > 0 && checkedCount != Rows.Count;
            if (_allRowCheckbox.IsThreeState)
            {
                _allRowCheckbox.IsChecked = null;
            }
            else
            {
                _allRowCheckbox.IsChecked = checkedCount == Rows.Count;
            }
            CanDeleteSelected = Rows.Any(p => p.Checked);
        }


        public void AllRowCheckBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckbox = (CheckBox)sender;
        }

        public void AllRowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckboxProcess = true;
            var cbx = ((CheckBox)sender);
            cbx.IsThreeState = !cbx.IsChecked.HasValue;
            if (cbx.IsChecked != null && cbx.IsChecked.HasValue)
            {
                foreach (var row in Rows)
                {
                    row.Checked = cbx.IsChecked.GetValueOrDefault();
                }
            }
            _allRowCheckboxProcess = false;
            CanDeleteSelected = Rows.Any(p => p.Checked);
        }

        public async void ExecuteGetListCmd(bool? isExport)
        {
            Loading = true;
            using var ctrl = new ICCardController();

            var paged = await ctrl.Pages(Search, Pagination.Current, Pagination.PageSize);

            Loading = false;

            Pagination.Total = paged.TotalCount;

            Rows = new BindableCollection<ICCard>(AJAutoMapperService.Instance()
                .Mapper.Map<List<Common.EF.Tables.ICCard>, List<ICCard>>(paged.Data));
        }

        #endregion

        public void QueryICCard()
        {
            if (Globalspace._dcWrite == -1)
            {
                Globalspace._dcWrite = _icSvc.InitIC(101);
                if (Globalspace._dcWrite < 0)
                {
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.未检测到读卡器请连接读卡器));
                    return;
                }
            }

            ulong icCardNo = 0;

            Services.ICCard.dc_card(Globalspace._dcWrite, (char)0, ref icCardNo);
            Services.ICCard.dc_beep(Globalspace._dcWrite, 10);

            _currentReadCardId = icCardNo.ToString();
            if (icCardNo != 0)
            {
                Current = Rows.FirstOrDefault(i => i.CardId == _currentReadCardId);
                if (Current != null)
                {

                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.查询到IC卡_0_, Current.CardId));
                }
                else
                {
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.此IC卡未绑定信息请写卡));
                }

                _currentReadCardId = string.Empty;
            }
            else
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.未检测到_0_, I18NService.Translate(LangKeys.IC卡)));
            }
        }

        public void WriteICCard()
        {
            if (Globalspace._dcWrite == -1)
            {
                Globalspace._dcWrite = _icSvc.InitIC(101);
                if (Globalspace._dcWrite < 0)
                {
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.未检测到读卡器请连接读卡器));
                    return;
                }
            }

            ulong icCardNo = 0;

            Services.ICCard.dc_card(Globalspace._dcWrite, (char)0, ref icCardNo);
            Services.ICCard.dc_beep(Globalspace._dcWrite, 10);
            _currentReadCardId = icCardNo.ToString();
            if (icCardNo != 0)
            {
                Current = Rows.FirstOrDefault(i => i.CardId == _currentReadCardId);

                OpenForm(Current == null);
                _currentReadCardId = string.Empty;
            }
            else
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.未检测到_0_, I18NService.Translate(LangKeys.IC卡)));
            }
        }
    }
}
